<?php

namespace app\admin\controller;

use app\model\TrademarkOrder;
use think\exception\ValidateException;
use app\model\Order;
use app\model\OrderStaff;
use app\model\Store;
use app\model\OrderStatus;
use app\model\Express;
use app\model\OrderHistory;
use app\model\OrderExpress;
use app\model\Technical;
use app\model\Message;
use app\model\Paymethod;
use app\model\RegisterField;
use app\model\Category;
use app\model\Operatingcity;
use app\model\Goods;
use app\model\Area;

class OrderController extends Base
{

	function index()
	{
		$weid = weid();
		$path = input('post.path');
		$page = input('post.page', 1, 'intval');
		$keyword = input('post.keyword', '', 'serach_in');
		$status = input('post.status');
		$uid = input('post.uid');
		$create_time = input('post.create_time', '', 'serach_in');
		$query = Order::where(['weid' => $weid]);

		if (!empty($uid)) {
			$query->where('uid', $uid);
		}
		if (!empty($this->sid)) {
			$query->where('sid', $this->sid);
		}
		if (!empty($this->ocid)) {

			$Operatingcitydata = Operatingcity::find($this->ocid);
			if ($Operatingcitydata) {
				$Operatingcitydata = $Operatingcitydata->toArray();

				if ($Operatingcitydata['areatype'] == 2) {
					$query->where('shipping_district_name_two', $Operatingcitydata['district_name']);
				} elseif ($Operatingcitydata['areatype'] == 1) {
					$query->where('shipping_city_name_two', $Operatingcitydata['city_name']);
				}
			}
		}

		if ($path == '/order/service') {
			$query->where('ptype', 2)->where('is_times', 0);
		} elseif ($path == '/order/timescard') {
			$query->where('ptype', 2)->where('is_times', 1);
		} elseif ($path == '/order/goods') {
			$query->where('ptype', 1)->where('is_times', 0);
		}

		$query->with(['member', 'orderGoods', 'paymethod']);

		if (!empty($create_time)) {
			$query->where('create_time', 'between', [strtotime($create_time[0]), strtotime($create_time[1])]);
		}
		if (!empty($keyword)) {
			$query->where('name|pay_subject|shipping_tel|order_num_alias', 'like', '%' . $keyword . '%');
		}
		
		$querycount = clone $query;
		$countdata['statuscount1'] = Order::statuscount(clone $querycount,1);
		$countdata['statuscount2'] = Order::statuscount(clone $querycount,2);
		$countdata['statuscount3'] = Order::statuscount(clone $querycount,3);
		$countdata['statuscount4'] = Order::statuscount(clone $querycount,4);
		$countdata['statuscount5'] = Order::statuscount(clone $querycount,5);
		$countdata['statuscount6'] = Order::statuscount(clone $querycount,6);
        $countdata['statuscount8'] = Order::statuscount(clone $querycount,8);
		if (!empty($status)) {
			$query->where('order_status_id', $status);
		}

		$res = $query->order('id desc')
			->paginate(getpage())
			->toArray();

		foreach ($res['data'] as &$vo) {

			$vo['sid'] = Store::getTitle($vo['sid']);
			$vo['staff'] = OrderStaff::staff($vo['id']);
			$vo['create_time'] = time_format($vo['create_time']);
			$vo['pay_time'] = time_format($vo['pay_time']);

			if (empty($vo['orderGoods'])) {
				if (!empty($vo['cat_id'])) {
					$vo['orderGoods'][0]['image'] = Category::getImage($vo['cat_id']);
				}
				$vo['orderGoods'][0]['name'] = '【用户发布需求】' . $vo['pay_subject'];
			}
			if ($vo['ptype'] == 1) {
				$vo['order_status'] = OrderStatus::get_order_status_name($vo['order_status_id']);
			} else {
				$vo['order_status'] = OrderStatus::get_order_status_name_yuyue($vo['order_status_id']);
			}

            if($vo['payment_code'] == "balance"){
                $vo['payment_code_name'] = 	'余额支付';
            }else{
                $vo['payment_code_name'] = 	Paymethod::get_paymethod_name($vo['payment_code']);
            }

			$vo['shipping_type'] = getdeliverymode($vo['deliverymode']);

			if ($vo['is_times'] == 1) {

				if ($vo['timesdate']) {
					if ($vo['timestype'] == 1) {
						$vo['yue_time'] = '每月:' . $vo['timesdate'] . '号';
					} else {
						$vo['yue_time'] = '每周周:' . $vo['timesdate'];
					}
				} else {
					$vo['yue_time'] = '还没有预约时间';
				}
			} else {
				$vo['yue_time'] = time_format($vo['beginTime']) . ' 到 ' . date('H:i', $vo['endTime']);
			}

            $vo['fwaddress'] = $vo['shipping_district_name_two'].$vo['shipping_city_name_two'];
			if (!empty($vo['orderGoods'])) {

				foreach ($vo['orderGoods'] as &$vvo) {
					$vvo['image'] = toimg($vvo['image']);
				}
			}
		}

		$data['data'] = $res;
		$data['countdata'] = $countdata;

		return $this->json($data);
	}

    function trademark()
    {
        $weid = weid();
        $orderModel = new TrademarkOrder();
        $page = input('post.page', 1, 'intval');
        $keyword = input('post.keyword', '', 'serach_in');
        $status = input('post.status');
        $uid = input('post.uid');
        $create_time = input('post.create_time', '', 'serach_in');
        $query = $orderModel->where(['weid' => $weid]);

        if (!empty($uid)) {
            $query->where('uid', $uid);
        }

        $query->with(['member', 'paymethod','trademark']);

        if (!empty($create_time)) {
            $query->where('create_time', 'between', [strtotime($create_time[0]), strtotime($create_time[1])]);
        }
        if (!empty($keyword)) {
            $query->where('name|shipping_tel|order_num_alias', 'like', '%' . $keyword . '%');
        }

        $querycount = clone $query;
        $countdata['statuscount1'] = Order::statuscount(clone $querycount,1);
        $countdata['statuscount5'] = Order::statuscount(clone $querycount,5);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }
        $res = $query->order('order_status_id desc')
            ->paginate(getpage())
            ->toArray();

        foreach ($res['data'] as &$vo) {
            $vo['create_time'] = time_format($vo['create_time']);
            $vo['pay_time'] = time_format($vo['pay_time']);

            $vo['order_status'] = OrderStatus::get_order_status_name($vo['order_status_id']);
            if($vo['payment_code'] == "balance"){
                $vo['payment_code_name'] = 	'余额支付';
            }else{
                $vo['payment_code_name'] = 	Paymethod::get_paymethod_name($vo['payment_code']);
            }
            $vo['fwaddress'] = $vo['shipping_province_name'].$vo['shipping_city_name'].$vo['shipping_district_name'];
        }

        $data['data'] = $res;
        $data['countdata'] = $countdata;

        return $this->json($data);
    }



	public function total()
	{

		$postdata = input('post.');
		$skumore = json_decode($postdata['skumore'], true);
		$Goods = new Goods;
		$buygoods = $Goods->cartGoods([
			'id' => $postdata['goods_id'],
			'sku' => $postdata['sku'],
			'quantity' => $postdata['number'],
			'is_skumore' => $postdata['is_skumore'],
			'skumore' => $skumore
		]);
		$data["amountTotle"] = $buygoods['total'];
		$data["amountTotle"] = round($data["amountTotle"], 2);

		return $this->json(['data' => $data]);
	}

	function add()
	{
		$msg = '添加成功';
		$postdata = input('post.');
		$ordermod = new Order;

		$payment = 'offline_pay';

		$servicetime = input('post.servicetime');
		$servicetime =  explode(' ', $servicetime);
		$timetmp = explode('-', $servicetime[1]);

		$order['beginTime'] = strtotime($servicetime[0] . ' ' . $timetmp[0]);
		$order['endTime'] = strtotime($servicetime[0] . ' ' . $timetmp[1]);
		$order['goods_id'] = $postdata['goods_id'];
		$order['total'] = $postdata['total'];
		$order['number'] = $postdata['number'];

		//支付方式
		if (!empty($payment)) {
			$order['payment_code'] = $payment;

			$paymentdata = Paymethod::where(['code' => $payment, 'weid' => weid()])->find();

			$order['pay_method_id'] = $paymentdata->id;
		}

		$area = $postdata['area'];
		$order['shipping_province_name'] = Area::get_area_name($area[0]);
		$order['shipping_city_name'] = Area::get_area_name($area[1]);
		$order['shipping_district_name'] = Area::get_area_name($area[2]);

		$order['shipping_name'] = $postdata['shipping_name'];
		$order['shipping_tel'] = $postdata['shipping_tel'];
		$order['shipping_address'] = $postdata['shipping_address'];

		$order['remark'] = $postdata['remark'];

		//var_dump($order);

		$data = $ordermod->add_order($order);

		if (!empty($data['id'])) {

			$pay_time = time();
			Order::where(['id' => $data['id']])->update(['pay_time' => $pay_time]);

			$ordermod = new Order;
			$ordermod->pay_order(['id' => $data['id']]);
		}

		return $this->json(['msg' => $msg, 'data' => $data]);
	}

	function update()
	{
		$msg = '修改成功';
		$postdata = input('post.');
		$orderInfo = $postdata['orderInfo'];


		if ($orderInfo['order_status_id'] == 2) {
			$order_history['order_status_id'] = 3;
			$orderup['order_status_id'] = 3;
		} else if ($orderInfo['order_status_id'] == 8) {
			$order_history['order_status_id'] = 9;
			$orderup['order_status_id'] = 9;
		}

		try {

			$order_history['order_id'] = $orderInfo['id'];
			$order_history['remark'] = $postdata['words'];
			$order_history['create_time'] = time();
			$order_history['notify'] = 1;

			OrderHistory::create($order_history);

			$orderup['is_express'] = $postdata['is_express'];

			$fieldsdata = RegisterField::fieldToData($postdata['fields']);
			$orderup['customtext'] = $fieldsdata['customtext'];
			$orderup['total'] = $orderInfo['total'];
			$orderup['id'] = $orderInfo['id'];
			order::update($orderup);
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		return $this->json(['msg' => $msg]);
	}

	function staff()
	{
		$postdata = input('post.');
		$orderInfo = $postdata['orderInfo'];
		if ($orderInfo['order_status_id'] == 2) {
			$order_history['order_status_id'] = 3;
			$orderup['order_status_id'] = 3;
		} else if ($orderInfo['order_status_id'] == 8) {
			$order_history['order_status_id'] = 9;
			$orderup['order_status_id'] = 9;
		}

		try {

			$order_history['order_id'] = $orderInfo['id'];
			$order_history['remark'] = '派单';
			$order_history['create_time'] = time();
			$order_history['notify'] = 1;
			OrderHistory::create($order_history);

			$order_staff['order_id'] = $orderInfo['id'];
			$order_staff['uuid'] = $postdata['uuid'];
			$order_staff['create_time'] = time();

			OrderStaff::addstaff($order_staff);
			Message::sendMiniStaff($orderInfo);
			Message::distribution($postdata['uuid'], $orderInfo);
			$msg = '派单成功';

			$orderup['sid'] = $orderInfo['sid'];
			$orderup['id'] = $orderInfo['id'];
			order::update($orderup);
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		return $this->json(['msg' => $msg]);
	}
	function send()
	{
		$postdata = input('post.');
		$orderInfo = $postdata['orderInfo'];

		if ($orderInfo['order_status_id'] == 2) {
			$order_history['order_status_id'] = 3;
			$orderup['order_status_id'] = 3;
		} else if ($orderInfo['order_status_id'] == 8) {
			$order_history['order_status_id'] = 9;
			$orderup['order_status_id'] = 9;
		}

		try {

			$order_history['order_id'] = $orderInfo['id'];
			$order_history['remark'] = $postdata['words'];
			$order_history['create_time'] = time();
			$order_history['notify'] = 1;
			OrderHistory::create($order_history);
			$order_express['weid'] = weid();
			$order_express['order_id'] = $orderInfo['id'];
			$order_express['expressname'] = Express::getExname($postdata['express_code']);
			$order_express['express_code'] = $postdata['express_code'];
			$order_express['express_no'] = $postdata['express_no'];
			$order_express['create_time'] = time();
			if (OrderExpress::where('order_id', $orderInfo['id'])->find()) {
				OrderExpress::where('order_id', $orderInfo['id'])->update($order_express);
				$msg = '修改物流信息成功';
			} else {
				OrderExpress::create($order_express);
				$msg = '发货成功';
			}

			$orderup['is_express'] = $postdata['is_express'];

			$orderup['id'] = $orderInfo['id'];
			order::update($orderup);
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		return $this->json(['msg' => $msg]);
	}

	function getSendInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');
		$orderInfo = Order::find($id);
		if ($orderInfo) {
			$orderInfo = $orderInfo->toArray();
		}

		$data = OrderExpress::where('order_id', $id)->find();
		if ($data) {
			$data = $data->toArray();
		}

		$data['orderInfo'] = $orderInfo;
		$data['is_express'] = $orderInfo['is_express'];

		return $this->json(['data' => $data]);
	}

	function offlinepay()
	{

		$postdata = input('post.');
		$orderInfo = $postdata['orderInfo'];

		$id = $orderInfo['id'];

		$orderinfo = Order::where(['id' => $id])->find();

		if (!empty($orderinfo)) {

			$pay_time = time();
			Order::where(['id' => $id])->update(['pay_time' => $pay_time]);

			$ordermod = new Order;
			$ordermod->pay_order(['id' => $id]);
		}
		return $this->json(['msg' => '操作成功']);
	}

	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');

		$data = Order::order_info($id);

		$data['sidarray'] = Store::getpcarray($data['orderInfo']['shipping_city_name_two']);
		$data['technical'] = Technical::getpcarray($data['orderInfo']['shipping_city_name_two']);
		if ($data['orderInfo']['payment_code'] == 'offline_pay') {
			$data['offline_img'] = Order::getoffline($id);
		}

		if ($data['orderInfo']['sid'] == 0) {
			$data['orderInfo']['sid'] = '';
		}
		if (empty($data['orderInfo']['member'])) {
			$data['orderInfo']['member'] = [];
		}
		$data['is_express']	= 1;

		$data['uuid'] = OrderStaff::getuuid($data['orderInfo']['id']);

		$customtext = iunserializer($data['orderInfo']['customtext']);

		$RegisterField = RegisterField::getinputField('complete');
		foreach ($RegisterField as &$vo) {

			if ($vo['is_sys'] == 1) {
			} else {
				$vo['fieldsvalue'] = $customtext[$vo['inputtype']][$vo['id']];
			}
		}
		$data['fields'] = $RegisterField;
		return $this->json(['data' => $data,'msg'=>$data['orderInfo']['shipping_city_name_two']]);
	}

    /**
     * @menu 订单详情
     * @Author:男人的坏
     * @Date:2024-04-01 15:00
     */
	function trademarkInfo(){
        $id =  $this->request->post('id', '', 'serach_in');
        if (!$id) throw new ValidateException('参数错误');
        $data = TrademarkOrder::order_info($id);
        return $this->json(['data' => $data,'msg'=>$data]);
    }

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
		Order::destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}

    function trademarkdelete()
    {
        $idx =  $this->request->post('id', '', 'serach_in');
        if (!$idx) throw new ValidateException('参数错误');
        TrademarkOrder::destroy(['id' => explode(',', $idx)], true);
        return $this->json(['msg' => '操作成功']);
    }
	function getTechnical()
	{
		$sid =  $this->request->post('sid', '', 'serach_in');
		$data['technical'] = Technical::getpcarray();

		return $this->json(['data' => $data]);
	}
	function getExpress()
	{
		$data['expressArray'] = Express::getpcarray();
		return $this->json(['data' => $data]);
	}


    /**
     * 驳回
     */

    public function reject_profile(){
        $ids               = input('post.orderid');
        if(!$ids){
            return $this->json(['message' => '缺少参数', 'errno' => 10010, 'data' => []]);
        }
        $orderInfo = Order::where(['id'=>$ids])->find();
        if(!$orderInfo){
            return $this->json(['message' => '订单不存在', 'errno' => 10010, 'data' => []]);
        }
        if($orderInfo->order_status_id != 8){
            return $this->json(['message' => '订单状态已被更改', 'errno' => 10010, 'data' => []]);
        }
        $orderInfo->order_status_id = 3;
        $orderInfo->profile_string  = '';
        $orderInfo->save();
        return $this->json(['message' => '操作成功']);
    }

    //完成

    public function complete()
    {
        $orderid = input('post.orderid');
        try {
            $data =  Order::complete($orderid);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }

        return $this->json(['data' => $data]);
    }
}
